import React, { Component, createRef } from 'react';
import {
  Form,
  Input,
  Button,
  Card,
  Row,
  Col,
  Cascader,
  Upload,
  Modal,
  notification,
} from 'antd';

import { PlusOutlined } from '@ant-design/icons';
import api from '../../../api/api';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default class AddProduct extends Component {
  state = {
    options: [],

    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: [],
    currentProduct: {},
    typeId: '',
    getData: false,
  };

  formRef = createRef();

  async findGoodsById(id) {
    let { data: res } = await api.goodsAPIs.findGoodsById(id);
    // console.log(res.data);

    res.data.type = [res.data.type.name];

    this.formRef.current.setFieldsValue({
      currentProduct: res.data,
    });
    // this.setState({
    //   getData: true,
    // });
  }

  async findAllCategroy() {
    let { data: res } = await api.catAPIs.findAllCategroy();

    this.setState({
      options: res.data,
    });
  }

  componentDidMount() {
    // console.log(this.props.match.params.id);
    this.findAllCategroy();
    this.findGoodsById(this.props.match.params.id);
  }

  // 级联
  onTypeChange = (value, selectedOptions) => {
    // console.log(selectedOptions);
    this.setState({
      typeId: selectedOptions[1].id,
    });
  };

  // Just show the latest item.
  // displayRender = label => {
  //   return label[label.length - 1];
  // };

  // 表单
  onFinish = values => {
    this.setState(
      {
        newProduct: {
          ...values,
          imgSrc: this.state.newProduct.imgSrc,
          type: this.state.typeId,
        },
      },
      async () => {
        console.log();
        let { data: res } = await api.catAPIs.addGoods(this.state.newProduct);
        if (res.code) {
          notification['success']({
            message: '添加成功',
            description: '添加商品已成功',
          });
          this.props.history.push('/products/products-list');
        }
      }
    );
    console.log('Success:', values);
  };

  onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
  };

  // 上传
  // 关闭预览
  handleCancel = () => this.setState({ previewVisible: false });
  // 点击预览
  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle:
        file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  handleChange = ({ file, fileList }) => {
    console.log(file);
    this.setState({
      fileList,
      newProduct: {
        ...this.state.newProduct,
        imgSrc: file.name,
      },
    });
  };

  render() {
    const {
      options,
      previewVisible,
      previewImage,
      fileList,
      previewTitle,
      currentProduct,
    } = this.state;

    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );

    return (
      <Card
        title="修改商品"
        extra={
          <Button
            type="link"
            onClick={() => {
              this.props.history.push('/products/products-list');
            }}
          >
            返回上一级
          </Button>
        }
      >
        <Row>
          <Col span={16}>
            <Form
              ref={this.formRef}
              name="basic"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              initialValues={currentProduct}
              onFinish={this.onFinish}
              onFinishFailed={this.onFinishFailed}
              autoComplete="off"
            >
              <Form.Item
                label="商品名称"
                name={['currentProduct', 'name']}
                rules={[{ required: true }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="商品类别"
                name={['currentProduct', 'type']}
                rules={[{ required: true }]}
              >
                <Cascader
                  options={options}
                  expandTrigger="hover"
                  onChange={this.onTypeChange}
                />
              </Form.Item>

              <Form.Item
                label="商品价格"
                name={['currentProduct', 'price']}
                rules={[{ required: true }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="商品描述"
                name={['currentProduct', 'title']}
                rules={[{ required: true, message: '输入商品名称' }]}
              >
                <Input.TextArea />
              </Form.Item>

              <Form.Item
                label="商品详情"
                name={['currentProduct', 'msg']}
                rules={[{ required: true, message: '输入商品名称' }]}
              >
                <Input.TextArea />
              </Form.Item>

              <Form.Item label="商品图片" name="imgSrc">
                <>
                  <Upload
                    action="http://web.woniulab.com:8002/goods/fileUpload"
                    listType="picture-card"
                    name="imgSrc"
                    initialValue={currentProduct.imgSrc}
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                  >
                    {fileList.length >= 8 ? null : uploadButton}
                  </Upload>
                  <Modal
                    visible={previewVisible}
                    title={previewTitle}
                    footer={null}
                    onCancel={this.handleCancel}
                  >
                    <img
                      alt="example"
                      style={{ width: '100%' }}
                      src={previewImage}
                    />
                  </Modal>
                </>
              </Form.Item>

              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  Submit
                </Button>
              </Form.Item>
            </Form>
          </Col>
        </Row>
      </Card>
    );
  }
}
